package cn.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 经典ABA问题 使用版本号验证 解决
 */
@Slf4j
public class ABATestPlus {
    private static AtomicStampedReference<String> str;
    public static void main(String[] args) throws InterruptedException {
        str=new AtomicStampedReference<>("A",0);
        int stamp=str.getStamp();
        other();
        Thread.sleep(1000);
        log.info("A->C    "+str.compareAndSet("A","c",stamp,stamp+1));//版本号肯定会检查不通过
        log.debug(String.valueOf(str.getStamp()));
    }
    static  void  other(){
        new Thread(()->{
            int one=str.getStamp();
            str.compareAndSet("A","B",one,one+1);
            log.info(String.valueOf(str.getStamp()));
        }).start();
        new Thread(()->{
            int one=str.getStamp();
            str.compareAndSet("B","A",one,one+1);
        }).start();
    }
}
